package com.apes.scm.stock.transfer.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.Arith;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.MapUtil;
import com.apes.pi.service.PiManager;
import com.apes.scm.account.account.service.StockService;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.sal.saleOrder.SaleOrder;
import com.apes.scm.sal.saleOrder.SaleOrderItem;
import com.apes.scm.sal.saleOrder.SaleOrderRepository;
import com.apes.scm.stock.transfer.model.Pick;
import com.apes.scm.stock.transfer.repository.PickRepository;
import com.apes.scm.voucher.model.Voucher;
import com.apes.scm.voucher.model.VoucherItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 通过交货单生成销售凭证
 * 分销模式上面存在多次交货，多次过账
 */
@Service
public class PickFlowMultiSaleVoucherService extends DomainService {

    @Autowired
    private SaleOrderRepository saleOrderRepository;
    @Value("${apes.switched:false}")
    private Boolean switched;

    public Voucher createByPickId(SimpleRequest request) {
        String id = request.get("id");
        Pick pick = SpringManager.getBean(PickRepository.class).findOne(id);

        SaleOrder saleOrder = saleOrderRepository.findOne(pick.getOrigin());
        if (saleOrder == null) throw new RuntimeException(pick.getOrigin() + "分销订单不存在！");

        return getVoucher(pick, saleOrder);
    }

    public Voucher flowSaleVoucher(SimpleRequest simpleRequest) {
        Pick pick = simpleRequest.getO(Pick.class);
        SaleOrder saleOrder = saleOrderRepository.findOne(pick.getOrigin());
        if (saleOrder == null) throw new RuntimeException(pick.getOrigin() + "分销订单不存在！");

        return getVoucher(pick, saleOrder);
    }

    private Voucher getVoucher(Pick pick, SaleOrder saleOrder) {
        Voucher voucher = new Voucher();
        voucher.setCompany(saleOrder.getCompany());
        voucher.setDept(saleOrder.getDept());
        voucher.setClerk(saleOrder.getClerk()); //业务员
        voucher.setContract(saleOrder.getContract());//采购合同
        voucher.setPartner(saleOrder.getCustomer().getParty().getPartyRoleByType("Customer"));
        voucher.setInventoryMode(saleOrder.getCooperation().getInventoryMode());
        voucher.setAccountingMethod(saleOrder.getCooperation().getAccountingMethod());
        voucher.setScene(saleOrder.getScene());
        voucher.setOrigin(saleOrder.getId());
        voucher.setOriginBusinessType(pick.getOriginBusinessType());
        voucher.setSource(pick.getId());
        voucher.setSourceBusinessType(pick.getInnerBusinessType());

        // 从表信息
        voucher.setVoucherItems(getVoucherItems(saleOrder, pick));
        return voucher;
    }

    public Set<VoucherItem> getVoucherItems(SaleOrder saleOrder, Pick pick) {
        Set<VoucherItem> voucherItems = new HashSet();
        Map<String, SaleOrderItem> orderItemMap = saleOrder.getSaleItems().stream()
                .filter(saleOrderItem -> !LogicalUtil.in(saleOrderItem.getProduct().getType(), "aut"))
                .collect(Collectors.toMap(SaleOrderItem::getId, SaleOrderItem -> SaleOrderItem));
        pick.getPickItems().forEach(
                pickItem -> {
                    VoucherItem voucherItem = new VoucherItem();
                    SaleOrderItem saleOrderItem = orderItemMap.get(pickItem.getOriginLine());
                    if (saleOrderItem == null) throw new RuntimeException("未找到采购订单行：" + pickItem.getOriginLine());

                    voucherItem.setProduct(pickItem.getProduct());
                    voucherItem.setTax(saleOrderItem.getTax());
                    voucherItem.setOwner(saleOrder.getLocation().getCompany());
                    voucherItem.setUom(saleOrderItem.getUom());
                    voucherItem.setProductQty(pickItem.getQtyDone());

                    //分销单取分销佣金
                    if ("FN_SALE".equals(saleOrder.getOrderType())) {
                        double commission = Arith.mul(voucherItem.getProductQty(), getSaleCommission(saleOrderItem.getProduct(), saleOrder.getCompany()));
                        voucherItem.setSaleCommission(commission);
                    }

                    voucherItem.setPriceUnit(saleOrderItem.computePriceUnit());
                    voucherItem.setOriginItemId(String.valueOf(saleOrderItem.getId()));
                    voucherItem.setSourceItemId(String.valueOf(pickItem.getId()));
                    voucherItems.add(voucherItem);
                });
        return voucherItems;
    }


    /**
     * 获取商品的分销佣金
     *
     * @param product 商品
     * @param company 公司
     * @return 佣金
     */
    public double getSaleCommission(Product product, PartyRole company) {
        if (switched) {
            return getNewSaleCommission(product, company);
        } else {
            return getOldSaleCommission(product, company);
        }
    }

    public double getOldSaleCommission(Product product, PartyRole company) {
        Map map = MapUtil.mapper(
                "SPID", product.getId(),
                "PLID", product.getClassify().getId(),
                "PPID", product.getBrand().getId(),
                "JLDW", product.getUom().getName(),
                "SYGSID", SpringManager.getBean(StockService.class).getPlatform(false, true, company, product).getId(),
                "DJGCID", "XS10"
        );
        JSONObject response = SpringManager.getBean(PiManager.class).synErp("ipmVipService.getDjgc", map);
        JSONObject commissionData = JSONObject.parseObject(response.getString("obj"));
        if (!commissionData.containsKey("F061")) {
            throw new RuntimeException("取分销佣金出错，请检分销策略！！！");
        }
        return commissionData.getDoubleValue("F061");
    }

    public double getNewSaleCommission(Product product, PartyRole company) {
        String ptId = SpringManager.getBean(StockService.class).getPlatform(false, true, company, product).getId();

        Map m = MapUtil.mapper(
                "PRODUCT_ID", product.getId(),
                "CLASSIFY_ID", product.getClassify().getId(),
                "BRAND_ID", product.getBrand().getId(),
                "PRODUCT_UOM_ID", product.getUom().getId(),
                "SYS_RQ", new Date(),
                "PUR_COMPANY_ID", ptId,
                "SYS_NO_CHECK", "SUPPLIER_ID",
                "conditionStrategyId","XS10"
        );
        Object obj = invoke("condition.execConditionStrategy", m);
        JSONObject result = new JSONObject(MapUtil.mapped(obj));
        if (!result.containsKey("F061")) {
            throw new RuntimeException("取分销佣金出错，请检分销策略！！！");
        }
        return result.getDoubleValue("F061");
    }

}


























